//
//  DiscoverViewModel.swift
//  aishop
//
//  Created by tuguowei on 2025/10/15.
//

import Foundation
import Combine

@MainActor
class DiscoverViewModel: ObservableObject {
    // 分类数据
    @Published var categories: [CommunityCategory] = []
    
    // 推荐页面数据
    @Published var recommendNotes: [CommunityNote] = []
    @Published var recommendAuthors: [RecommendAuthor] = []
    
    // 关注页面数据
    @Published var followNotes: [CommunityNote] = []
    
    // 分页状态
    @Published var recommendPage = 1
    @Published var followPage = 1
    @Published var isLoadingMore = false
    
    // 加载状态
    @Published var isLoading: Bool = false
    @Published var errorMessage: String?
    
    private var cancellables = Set<AnyCancellable>()
    private let apiService = APIService.shared
    private let pageLimit = 20
    
    // MARK: - 初始化数据加载
    func loadInitialData() async {
        isLoading = true
        errorMessage = nil
        
        do {
            // 并行加载分类和推荐作者数据
            async let categoriesResult = loadCategories()
            async let authorsResult = loadRecommendAuthors()
            
            let (categories, authors) = try await (categoriesResult, authorsResult)
            
            self.categories = categories
            self.recommendAuthors = authors
            
            // 加载推荐数据
            await loadRecommendData(categoryId: "")
            
            isLoading = false
        } catch {
            errorMessage = "加载数据失败: \(error.localizedDescription)"
            isLoading = false
        }
    }
    
    // MARK: - 加载推荐数据
    func loadRecommendData(categoryId: String = "") async {
        recommendPage = 1
        
        do {
            let response = try await apiService.getDiscoverList(
                categoryId: categoryId,
                page: recommendPage,
                limit: pageLimit
            )
            
            if response.isSuccess, let data = response.data {
                self.recommendNotes = data.list
            } else {
                errorMessage = response.message ?? "加载推荐数据失败"
            }
        } catch {
            print("加载推荐数据失败: \(error)")
            errorMessage = "加载推荐数据失败"
        }
    }
    
    // MARK: - 加载更多推荐数据
    func loadMoreRecommendData(categoryId: String = "") async {
        guard !isLoadingMore else { return }
        
        isLoadingMore = true
        recommendPage += 1
        
        do {
            let response = try await apiService.getDiscoverList(
                categoryId: categoryId,
                page: recommendPage,
                limit: pageLimit
            )
            
            if response.isSuccess, let data = response.data {
                let newNotes = data.list
                self.recommendNotes.append(contentsOf: newNotes)
            }
        } catch {
            print("加载更多推荐数据失败: \(error)")
            recommendPage -= 1 // 回退页码
        }
        
        isLoadingMore = false
    }
    
    // MARK: - 加载关注数据
    func loadFollowData() async {
        followPage = 1
        
        do {
            let response = try await apiService.getFollowList(
                page: followPage,
                limit: pageLimit
            )
            
            if response.isSuccess, let data = response.data {
                self.followNotes = data.list
            } else {
                errorMessage = response.message ?? "加载关注数据失败"
            }
        } catch {
            print("加载关注数据失败: \(error)")
            errorMessage = "加载关注数据失败"
        }
    }
    
    // MARK: - 加载更多关注数据
    func loadMoreFollowData() async {
        guard !isLoadingMore else { return }
        
        isLoadingMore = true
        followPage += 1
        
        do {
            let response = try await apiService.getFollowList(
                page: followPage,
                limit: pageLimit
            )
            
            if response.isSuccess, let data = response.data {
                let newNotes = data.list
                self.followNotes.append(contentsOf: newNotes)
            }
        } catch {
            print("加载更多关注数据失败: \(error)")
            followPage -= 1 // 回退页码
        }
        
        isLoadingMore = false
    }
    
    // MARK: - 私有方法
    
    // 加载分类
    private func loadCategories() async throws -> [CommunityCategory] {
        do {
            let response = try await apiService.getCommunityCategoryList()
            
            if response.isSuccess, let categories = response.data {
                return categories
            } else {
                throw APIError.serverError(response.message ?? "加载分类失败")
            }
        } catch {
            print("加载分类失败: \(error)")
            return []
        }
    }
    
    // 加载推荐作者
    private func loadRecommendAuthors() async throws -> [RecommendAuthor] {
        do {
            let response = try await apiService.getRecommendAuthorList()
            
            if response.isSuccess, let data = response.data {
                return data.list
            } else {
                throw APIError.serverError(response.message ?? "加载推荐作者失败")
            }
        } catch {
            print("加载推荐作者失败: \(error)")
            return []
        }
    }
}
